package top.pro51.bolg_admin.controller.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import top.pro51.bolg_admin.domain.User;
import top.pro51.bolg_admin.service.UserService;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/admin")
public class LoginController {


    @Autowired
    private UserService userService;

    /**
     * @Description 跳转到登陆页面
     * @Author WangWenpeng
     * @Date 1:03 2020/7/28
     * @Param []
     */
    @GetMapping
    public String loginPage() {
        return "admin/login";
    }

    /**
     * @Description 执行登录的方法
     * @Author WangWenpeng
     * @Date 1:03 2020/7/28
     * @Param [username, password, session, attributes]
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        User user = userService.checkUser(username, password);
        if (user != null) {
            user.setPassword(null);
            session.setAttribute("user", user);
            return "admin/index";
        } else {
            attributes.addFlashAttribute("message", "用户名和密码错误");
            return "redirect:/admin";
        }
    }

    /**
     * @Description 注销操作
     * @Author WangWenpeng
     * @Date 1:03 2020/7/28
     * @Param [session]
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
